Cocojunk

🚀 Dive deep with CocoJunk – your destination for detailed, well-researched articles across science, technology, culture, and more. Explore knowledge that matters, explained in plain English.

Navigation: Home

Interrupt

Published: Sat May 03 2025 19:14:06 GMT+0000 (Coordinated Universal Time) Last Updated: 5/3/2025, 7:14:06 PM

Read the original article here.


Interrupts: The Heartbeat of Modern Computing (for Builders)

In the journey of building a computer from scratch, understanding how the Central Processing Unit (CPU) interacts with the outside world and manages multiple tasks is crucial. One of the most fundamental mechanisms enabling this is the interrupt. Far from being a simple nuisance, interrupts are the sophisticated way your processor handles events that don't happen strictly in sync with the code it's currently executing.

1. What is an Interrupt?

At its core, an interrupt is a signal – either from hardware or software – that tells the CPU to temporarily stop what it's doing and attend to something else. Think of it like a critical incoming call that causes you to pause your current conversation.

Definition: Interrupt A signal to the processor to suspend its current execution and transfer control to a special routine called an interrupt handler or interrupt service routine (ISR). This allows the processor to respond to external events or handle specific conditions in a timely manner.

Interrupts are essential because the world outside the CPU (devices like keyboards, mice, hard drives, network cards, timers) operates asynchronously. If the CPU had to constantly ask each device if it needed attention (a method called polling), it would waste enormous amounts of time and be unable to do anything else efficiently. Interrupts allow devices to signal the CPU only when they require service.

2. The Interrupt Mechanism: How the CPU Responds

When an interrupt signal is detected, the CPU doesn't just halt. It follows a specific sequence of steps to ensure that it can return to its original task later:

  1. Detect the Interrupt: The CPU constantly checks for interrupt signals at the end of each instruction execution cycle.
  2. Acknowledge (if necessary): For some hardware interrupts, the CPU might send an acknowledgment signal back to the interrupting device or controller.
  3. Suspend Current Execution: The CPU stops executing the instruction stream it was following.
  4. Save Processor State: This is a critical step. To resume the interrupted task later, the CPU must save its current state. This typically includes:
    • The Program Counter (PC), which points to the next instruction that would have been executed.
    • All or a relevant subset of its general-purpose registers.
    • Processor status flags (like carry, zero, interrupt enable/disable status).
    • Often, this state is pushed onto a dedicated stack (the interrupt stack) or saved to specific memory locations.
  5. Determine the Interrupt Source/Type: The CPU needs to know what caused the interrupt to find the correct handler. This can be done in various ways depending on the architecture (see Interrupt Vector Table below).
  6. Load the Interrupt Handler Address: Based on the interrupt type, the CPU loads the memory address of the corresponding Interrupt Service Routine (ISR) or Interrupt Handler into the Program Counter.
  7. Execute the Interrupt Handler: The CPU now executes the code in the ISR. This code's job is to deal with the specific event that caused the interrupt (e.g., read data from a keyboard buffer, service a timer, handle a memory error).
  8. Restore Processor State: Once the ISR finishes its task, it typically executes a special instruction (often IRET or RETFIE - Return From Interrupt) that tells the CPU to:
    • Pop the previously saved state (PC, registers, flags) from the stack or memory.
    • Restore the CPU to the exact state it was in before the interrupt occurred.
  9. Resume Original Execution: The CPU loads the saved PC, and execution continues from the instruction that was about to run when the interrupt occurred.

Definition: Interrupt Service Routine (ISR) or Interrupt Handler A specific block of code that is executed by the processor when a particular type of interrupt occurs. The ISR contains the instructions necessary to handle the event that triggered the interrupt.

3. Why Use Interrupts? (vs. Polling)

Imagine writing code for your scratch-built computer to read input from a keyboard.

  • Polling Approach: Your main program loop would need to repeatedly check a specific hardware register associated with the keyboard controller: "Is there a key pressed? No? Is there a key pressed? No?...". This loop would consume CPU cycles constantly, even when no key is pressed. While polling is simpler to implement for very basic systems or for infrequent, non-critical checks, it's highly inefficient for the CPU when dealing with many potential events.
  • Interrupt-Driven Approach: The main program does its work. The keyboard controller hardware, when a key is pressed, asserts an interrupt line connected to the CPU. The CPU is interrupted, jumps to the keyboard ISR. The ISR reads the key data from the keyboard controller register and stores it in a buffer. The ISR finishes, and the CPU returns to its main task. The main program can then check the buffer whenever it needs keyboard input. This frees the CPU to do other things while waiting for input.

Interrupts are crucial for:

  • Responsiveness: Allowing the system to react quickly to external events (like a mouse click or network packet).
  • Efficiency: Preventing the CPU from wasting cycles constantly checking devices.
  • Concurrency/Multitasking: Enabling the operating system (if you build one!) to switch between different tasks based on timer interrupts or I/O completion interrupts.
  • Handling Errors: Signaling the CPU about unexpected events like division by zero or invalid memory access.

4. Types of Interrupts

Interrupts are broadly categorized based on their origin:

4.1 Hardware Interrupts

These are triggered by external hardware devices (or components within the CPU not directly tied to instruction execution, like a timer). They are typically asynchronous, meaning they can occur at any time, independent of the CPU's current instruction flow.

  • Trigger Source: Devices like keyboard controllers, disk controllers, network interfaces, timers, peripheral chips.
  • Mechanism: A device asserts a specific signal line (often called an Interrupt Request Line or IRQ line) connected to the CPU or an interrupt controller.
  • Asynchronous Nature: The interrupt signal can arrive at any moment relative to the CPU clock or instruction execution. The CPU synchronizes the request internally and acts on it at the next instruction boundary.
  • Identification: On simple systems, multiple devices might share a single interrupt line, and the ISR has to query each potential source. On more complex systems, an interrupt vector table is used. This table is a list of addresses in memory, where each entry corresponds to a specific interrupt type or source. When an interrupt occurs, the hardware (or an interrupt controller) provides an "interrupt vector" (an index into the table), and the CPU directly jumps to the ISR address found at that index.

Definition: IRQ (Interrupt Request) Line A physical signal line on a computer bus or directly connected to the CPU used by a hardware device to signal that it requires attention by asserting the line to a specific voltage level or by sending a pulse.

Definition: Interrupt Vector Table A data structure (usually an array or table in memory) that maps interrupt numbers or vectors to the memory addresses of their corresponding Interrupt Service Routines (ISRs). When an interrupt occurs, the CPU uses the interrupt vector provided by the hardware or interrupt controller to find the address of the ISR to execute.

4.1.1 Masking Hardware Interrupts

Not all hardware interrupts are equally critical. Processors have mechanisms to temporarily ignore or defer less important interrupts.

  • Interrupt Mask Register: CPUs typically have a special control register (or flags) called an interrupt mask register. This register has individual bits that can be set or cleared to enable or disable (mask) specific interrupt sources or groups of sources.
    • Masking: Disabling an interrupt source so that the CPU ignores its interrupt requests. The request might be held pending by hardware, or it might be lost depending on the design.
    • Unmasking: Re-enabling an interrupt source.
  • Maskable Interrupts: Most hardware interrupts are maskable. This allows the operating system or critical code sections (like inside an ISR that is currently handling a different, higher-priority interrupt) to prevent lower-priority interrupts from interrupting them.
  • Non-Maskable Interrupts (NMIs): Some interrupts are designed to always be serviced, regardless of the interrupt mask. These are reserved for catastrophic events that the system must respond to immediately, such as a power failure warning, a major hardware error, or a watchdog timer timeout (indicating the system has frozen). Even NMIs can sometimes be temporarily blocked by the CPU in extremely critical sections of code, but generally, they override the standard interrupt mask.

Definition: Interrupt Mask A mechanism (usually a bit in a CPU register) that allows specific interrupt sources to be temporarily ignored or deferred by the processor. Masked interrupts are disabled.

Definition: Non-Maskable Interrupt (NMI) A type of hardware interrupt that cannot be disabled or ignored by the standard interrupt mask. It is reserved for high-priority, critical events.

4.1.2 Hardware Interrupt Issues

When building or working with low-level hardware, you might encounter specific problems related to interrupts:

  • Missing Interrupts: A device changes state and should generate an interrupt, but fails to do so (due to a hardware bug, timing issue, or misconfiguration). If software is waiting for this interrupt (e.g., waiting for a disk transfer complete signal), it can hang indefinitely. Robust systems often use timeouts or alternative polling mechanisms to detect such failures.
  • Spurious Interrupts: The CPU receives an interrupt signal, but when the ISR runs, it finds no device actually requesting service. This can happen due to electrical noise, faulty wiring, or, commonly, timing issues in shared interrupt lines using certain triggering methods (see Level-Triggered issues below). A well-written ISR should always check all potential sources on a shared line to see which one actually interrupted, and if none are found, safely exit.

4.2 Software Interrupts

These interrupts are initiated by the processor itself, either upon executing a specific instruction designed to cause an interrupt, or when certain predefined conditions are met during instruction execution. They are synchronous, meaning they occur directly as a result of executing a particular instruction.

  • Trigger Source:
    • Explicit Instruction: A special instruction (e.g., INT on x86, SVC or SWI on ARM) is executed by the program. This is a common way for user programs to request services from the operating system kernel, which runs at a higher privilege level.
    • Program Error/Exceptional Condition: The CPU detects an error or an unusual condition while executing an instruction. Examples include:
      • Division by zero.
      • Attempting to access an invalid memory address (e.g., outside the program's allocated space - a segmentation fault).
      • Attempting to execute an invalid or privileged instruction from user mode.
      • A page fault (when the program tries to access a memory page that is not currently in physical RAM, requiring the OS to load it from disk).
  • Mechanism: The CPU detects the condition during instruction execution, saves state, determines the cause (often via an internal vector or exception code), and jumps to a corresponding ISR (often called an Exception Handler).
  • Use Cases:
    • System Calls: User programs use software interrupts (via specific instructions) to transition into kernel mode and request OS services (like opening a file, writing to the screen, allocating memory).
    • Exception Handling: The OS kernel's exception handlers deal with program errors. Depending on the error, the kernel might terminate the program, deliver a signal to the program (allowing it to potentially handle the error), or in severe cases, if the error occurs within the kernel itself, cause a system crash.
    • Instruction Emulation: An OS can use illegal instruction exceptions to emulate instructions that are not implemented in hardware on a particular CPU model. The exception handler detects the unimplemented instruction and executes the equivalent logic in software.

Definition: Software Interrupt An interrupt triggered by the CPU itself, either by executing a special instruction or by detecting an exceptional condition or error during instruction execution.

Definition: Exception A type of synchronous software interrupt triggered by an exceptional condition or error detected by the CPU during instruction execution (e.g., division by zero, page fault, illegal instruction).

Definition: System Call A mechanism by which a user-space program requests a service from the operating system kernel. On many architectures, this is implemented using a software interrupt or a dedicated instruction that causes a trap to the kernel.

5. Terminology Variations (Be Aware!)

The terms "interrupt," "trap," "exception," "fault," and "abort" are sometimes used interchangeably, but they often have more specific meanings depending on the CPU architecture or context. When building or working with a specific architecture (like x86, ARM, or a simple custom CPU), it's essential to understand its definitions.

  • Interrupt: Often used as the general term, but sometimes specifically refers to asynchronous hardware interrupts.
  • Trap: Can be a synonym for any interrupt or software interrupt. On some systems (like x86), it specifically means a synchronous event after the trapping instruction, often used for debuggers or system calls (the return address points to the next instruction).
  • Exception: Often refers to synchronous software interrupts caused by execution errors (like faults or aborts).
  • Fault: A synchronous exception that is generally "restartable." The instruction that caused the fault can typically be re-executed after the fault is handled (e.g., a page fault, where the OS loads the page and then the instruction is retried). On x86, the return address points to the faulting instruction.
  • Abort: A synchronous exception indicating a severe, non-restartable error (e.g., critical hardware failure, invalid system table value). Program execution usually cannot resume.

For your scratch build, you might define your own clear terminology!

6. Triggering Methods for Hardware Interrupts

The physical signal on an IRQ line needs to be interpreted by the CPU or interrupt controller. There are two primary methods:

6.1 Level-Triggered Interrupts

The interrupt is requested by holding the interrupt signal line at a specific active logic level (either high or low).

  • How it works: A device asserts the line to the active level and keeps it there until the CPU services the device. After servicing, the CPU typically commands the device to deassert the line.
  • Detection: The CPU or controller continuously samples the line. If the active level is detected, an interrupt is pending.
  • Sharing: Multiple devices can share a single level-triggered interrupt line using a wired-OR connection (or wired-AND, depending on active-low/high). If any device on the line asserts it, the line goes to the active level.
    • Challenge with Sharing: The ISR must poll all devices connected to the shared line to find which one(s) need service. After servicing one, it must poll again before returning, because another device might still be asserting the line, or a different device might have asserted it while the first was being serviced. If the ISR doesn't poll again, or if a device fails to deassert the line, the interrupt request persists, potentially causing a loop or spurious interrupts if not handled carefully.
  • Spurious Interrupts: As mentioned before, wired-OR and level sensitivity are prone to spurious interrupts if the timing is off or if the line doesn't return to the quiescent state quickly enough after the ISR services a device.

Definition: Level-Triggered Interrupt An interrupt requested by holding the interrupt signal line at a specific active logic level (high or low). The interrupt request persists as long as the signal remains at the active level.

Definition: Wired-OR (or Wired-AND) A circuit configuration where multiple device outputs are connected together on a single line via open collector or open drain outputs. This allows any device to pull the line to a specific voltage (the active level for a level-triggered interrupt) while letting it float (pulled to the inactive level by a resistor) when no device is actively asserting it.

6.2 Edge-Triggered Interrupts

The interrupt is signaled by a transition (edge) on the interrupt line – either a rising edge (low to high) or a falling edge (high to low).

  • How it works: A device sends a brief pulse (a transition followed by a return to the inactive state) on the line. The interrupt is triggered by the event of the transition, not the sustained level.
  • Detection: The CPU or controller includes latching circuitry that "remembers" that an edge occurred. The interrupt request is held in this latch until the CPU services it.
  • Sharing: Multiple devices can share an edge-triggered line if implemented correctly (e.g., using wired-OR/open collector to combine pulses). Each device sends a pulse. The issue is that pulses from different devices might merge, or an interrupt might be missed if interrupts are masked when the edge occurs and the hardware doesn't latch the request.
    • Missing Interrupts: If the CPU is configured to only respond to edges and is busy or interrupts are masked during the brief moment the pulse occurs, and the hardware doesn't latch the event, the interrupt request is lost.
  • Advantages: Less susceptible to spurious interrupts from persistent signals. Handling one device's interrupt doesn't prevent other devices from signaling new edge events (though the handling might be delayed until the current ISR finishes).

Definition: Edge-Triggered Interrupt An interrupt signaled by a transition (a rising or falling edge) on the interrupt signal line. The interrupt is triggered by the change in level, and the request is typically latched by hardware.

6.3 Hybrid Triggering

Some systems use a combination, checking for both an edge and ensuring the signal remains active for a minimum duration. This can help filter out spurious signals caused by noise, as seen with some NMI implementations.

6.4 Message-Signaled Interrupts (MSI)

More modern systems (like those using PCI Express) use a different approach. Instead of a dedicated physical wire per interrupt or shared wires, a device signals an interrupt by sending a special message over the data bus.

  • How it works: The device writes a specific value to a specific memory address range that is mapped to an interrupt controller. This write operation itself triggers the interrupt mechanism.
  • Advantages:
    • Eliminates the need for dedicated IRQ wires, simplifying board layout and increasing the number of interrupts available.
    • More flexible; messages can carry more information than a simple signal level/edge.
    • Easier to share and manage in complex systems.
  • Behavior: They behave conceptually similarly to edge-triggered interrupts – the event is a momentary signal (the message transmission) rather than a sustained level.

Definition: Message-Signaled Interrupt (MSI) A method where a device requests an interrupt by sending a message over a bus (like PCI Express) instead of asserting a dedicated physical interrupt line.

6.5 Doorbell Interrupts

This term is often used conceptually or for specific hardware mechanisms where software triggers hardware work by writing to a specific memory location.

  • How it works: Software writes data to a buffer in memory. Then, it writes to a special memory address or register (the "doorbell") that the hardware device is configured to monitor. This write to the doorbell location notifies the device that the data is ready.
  • Comparison: Similar to Message-Signaled Interrupts in that a memory write triggers action. The "doorbell interrupt" label can be a misnomer, as the hardware might poll the doorbell location, or the write might trigger a real hardware interrupt within the device's own internal processor (if it has one). The key is software initiating hardware action via memory.

Definition: Doorbell Interrupt (Conceptual/Mechanism) A pattern where software signals a hardware device that work is ready by writing to a specific memory address ("ringing the doorbell"). This write may or may not directly cause a traditional hardware interrupt on the main CPU, but it serves a similar purpose of asynchronously notifying the device.

6.6 Inter-Processor Interrupts (IPI)

In systems with multiple CPUs or cores, one processor can send a special interrupt message to another processor to get its attention. This is used for tasks like synchronizing caches, distributing work, or signaling events between cores.

7. System Implementation: Connecting Devices to the CPU

How do all these interrupt signals get to the CPU?

  • Direct Connection: In very simple systems, a few devices might have dedicated IRQ lines directly connected to interrupt pins on the CPU.
  • Programmable Interrupt Controller (PIC): More complex systems use a dedicated chip called a PIC (like the 8259 PIC used in early PCs). The PIC has multiple interrupt request inputs (IRQs) connected to various devices. It manages these requests (prioritizing them, handling masking) and asserts a single interrupt line to the CPU when a device needs attention. The CPU then interacts with the PIC to determine which device interrupted and get the vector number.
  • Integrated Controllers: Modern CPUs often integrate interrupt controller logic directly onto the chip or within a supporting chip like the southbridge or platform controller hub (PCH). These controllers multiplex requests from many devices onto the CPU's interrupt inputs and provide vectoring information.
  • System on a Chip (SoC): In SoCs, interrupts from different internal blocks are routed to an integrated interrupt controller that manages delivery to one or more processor cores.
  • Memory Mapping: Sometimes, interrupt controllers are mapped into the system's memory or I/O address space. The CPU interacts with the controller (masking interrupts, getting status, acknowledging) by reading from and writing to these specific memory/I/O addresses.

Understanding the interrupt controller hardware is vital for building a system, as it determines how devices are wired up and how the CPU discovers which device interrupted.

8. Practical Considerations for Builders

  • Prioritization: Many interrupt controllers and CPUs support interrupt priorities. Higher-priority interrupts can interrupt lower-priority ISRs. This is crucial for ensuring that time-sensitive events (like a fast network connection or a critical timer) are handled promptly, even if a less critical task (like disk I/O) is currently being serviced.
  • Reentrancy: ISRs must be carefully written. If an ISR can be interrupted by a higher-priority interrupt, the nested ISR must not corrupt the state or data structures being used by the interrupted ISR. Non-reentrant code can lead to crashes. Often, parts of an ISR run with interrupts disabled (masked) to prevent reentrancy issues in critical sections.
  • Atomicity: Operations within an ISR, or operations in the main code that interact with data modified by an ISR, may need to be atomic (indivisible) to prevent race conditions. Temporarily disabling interrupts is a common way to ensure atomicity for small code blocks.
  • Latency: The time taken from a device asserting an interrupt signal to the CPU starting the ISR is called interrupt latency. Minimizing this is important for real-time systems. Factors affecting latency include the CPU's interrupt detection mechanism, the interrupt controller's processing time, and whether interrupts are currently masked by higher-priority activity.
  • Shared Interrupts (Again): Sharing IRQ lines (especially level-triggered ones) requires careful software handling within the ISR to poll all potential sources and manage potential spurious interrupts. Edge-triggered sharing is simpler in terms of polling but risks missing interrupts if not latched by hardware. Message-signaled interrupts largely alleviate sharing issues. When designing hardware, consider the implications of shared lines.

9. Typical Uses in a Computer System

Interrupts are ubiquitous in modern computing. Examples include:

  • Timers: Periodic interrupts from a timer chip are used by the OS for scheduling tasks, keeping track of time, or triggering regular updates (e.g., screen refresh).
  • I/O Completion: Devices like disk controllers, network interfaces, and UARTs (serial ports) generate interrupts when a requested operation is finished (e.g., data has been read from the disk, a network packet has arrived, a character has been sent/received). This allows the CPU to initiate the operation and then do other work, being notified by interrupt when the data is ready or the device is free.
  • Input Devices: Keyboard presses and mouse movements generate interrupts, allowing the OS to capture input without constantly polling the devices.
  • System Management: Power-off signals, hardware errors, and watchdog timer expirations use interrupts (often NMIs) to signal critical events.
  • Multitasking/Context Switching: Operating systems use timer interrupts to regain control from a running process and decide if it's time to switch to another task. I/O completion interrupts signal that a process waiting for I/O can now be made ready to run.
  • Exception Handling: Software interrupts (exceptions) handle programming errors like division by zero, illegal memory access (page faults, segmentation faults), or invalid instructions. The OS can often handle these, sometimes transparently (page faults) or by terminating the faulty program.
  • System Calls: As mentioned, user programs request services from the kernel using software interrupts or dedicated trap instructions.

10. Interrupts vs. Signals (OS Context)

While related, it's important to distinguish interrupts (hardware/CPU mechanism handled by the kernel) from signals (an OS mechanism for inter-process communication).

  • Interrupts: Hardware- or CPU-generated events, handled by the operating system kernel's low-level handlers. They occur at the hardware/kernel boundary.
  • Signals: Software notifications sent between processes (or from the kernel to a process). They are an abstraction provided by the OS. While the OS kernel might receive an interrupt (like a segmentation fault exception), it often delivers this event to the offending process as a signal (like SIGSEGV) that the process can potentially catch and handle (though often the default action is program termination).

Understanding interrupts is fundamental to grasping how a CPU interacts with the physical world, manages multiple demands, and forms the basis upon which operating systems build more complex concepts like multitasking and process management. For anyone building a computer from scratch, mastering interrupt handling is a necessary step towards a functional and responsive system.

Related Articles

See Also